import { message } from 'antd';
import { post } from './request';

// 定义用户信息接口
export interface UserInfo {
  id: string;
  username: string;
  name: string;
  email: string;
  avatar?: string;
  roles: string[];
  permissions?: string[];
}

// 定义登录参数接口
export interface LoginParams {
  username: string;
  password: string;
  remember?: boolean;
}

// 定义登录响应接口
interface LoginResponse {
  token: string;
  user: UserInfo;
}

/**
 * 登录方法
 * @param params 登录参数
 * @returns Promise<UserInfo>
 */
export const login = async (params: LoginParams): Promise<UserInfo> => {
  try {
    const response = await post<LoginResponse>('/auth/login', params);
    
    // 保存token到localStorage
    localStorage.setItem('token', response.token);
    localStorage.setItem('isLoggedIn', 'true');
    
    // 保存用户信息到localStorage
    localStorage.setItem('userInfo', JSON.stringify(response.user));
    
    message.success('登录成功');
    return response.user;
  } catch (error) {
    message.error('登录失败，请检查用户名和密码');
    throw error;
  }
};

/**
 * 注销方法
 */
export const logout = async (): Promise<void> => {
  try {
    await post('/auth/logout');
  } catch (error) {
    console.error('Logout error:', error);
  } finally {
    // 无论API调用是否成功，都清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('userInfo');
    message.success('已安全退出');
    
    // 重定向到登录页
    window.location.href = '/login';
  }
};

/**
 * 获取当前用户信息
 * @returns UserInfo | null
 */
export const getCurrentUser = (): UserInfo | null => {
  const userInfoStr = localStorage.getItem('userInfo');
  if (!userInfoStr) return null;
  
  try {
    return JSON.parse(userInfoStr) as UserInfo;
  } catch (error) {
    console.error('Parse user info error:', error);
    return null;
  }
};

/**
 * 检查用户是否已登录
 * @returns boolean
 */
export const isAuthenticated = (): boolean => {
  return localStorage.getItem('isLoggedIn') === 'true' && !!localStorage.getItem('token');
};

/**
 * 检查用户是否有特定权限
 * @param permission 权限标识
 * @returns boolean
 */
export const hasPermission = (permission: string): boolean => {
  const user = getCurrentUser();
  if (!user || !user.permissions) return false;
  
  return user.permissions.includes(permission);
};

/**
 * 检查用户是否有特定角色
 * @param role 角色标识
 * @returns boolean
 */
export const hasRole = (role: string): boolean => {
  const user = getCurrentUser();
  if (!user || !user.roles) return false;
  
  return user.roles.includes(role);
};

/**
 * 更新用户信息
 * @param userInfo 用户信息
 */
export const updateUserInfo = (userInfo: Partial<UserInfo>): void => {
  const currentUser = getCurrentUser();
  if (!currentUser) return;
  
  const updatedUser = { ...currentUser, ...userInfo };
  localStorage.setItem('userInfo', JSON.stringify(updatedUser));
};